package com.filex.ads.banner;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

import com.filex.ads.common.AdError;
import com.filex.ads.common.AdFormat;
import com.filex.ads.common.logging.Logger;
import com.filex.ads.common.utils.Visibility;

public class FilexAdView extends FrameLayout {


    static final BannerAdListener EMPTY_NETWORK_LISTENER = new BannerAdListener() {

        @Override
        public void onAdLoaded(FilexAdView adView) {

        }

        @Override
        public void onAdLoadFailed(FilexAdView adView, AdError errorCode) {

        }

        @Override
        public void onAdClick(FilexAdView adView) {

        }

        @Override
        public void onAdImpression(FilexAdView adView) {

        }
    };

    private BannerAdListener mAdListener = EMPTY_NETWORK_LISTENER;

    @Nullable
    protected BannerAdController mAdViewController;

    private Context mContext;
    private int mScreenVisibility;
    private BroadcastReceiver mScreenStateReceiver;

    public FilexAdView(Context context) {
        this(context, null);
    }

    public FilexAdView( Context context,  AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FilexAdView(Context context,  AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        mScreenVisibility = getVisibility();

        setHorizontalScrollBarEnabled(false);
        setVerticalScrollBarEnabled(false);

        mAdViewController = new BannerAdController(context, this);
        registerScreenStateBroadcastReceiver();
    }

    public void setBannerAdListener(BannerAdListener listener) {
        mAdListener = listener;
    }

    public BannerAdListener getBannerAdListener() {
        return mAdListener;
    }


    private void registerScreenStateBroadcastReceiver() {
        mScreenStateReceiver = new BroadcastReceiver() {
            public void onReceive(final Context context, final Intent intent) {
                if (!Visibility.isScreenVisible(mScreenVisibility) || intent == null) {
                    return;
                }

                final String action = intent.getAction();

                if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    setAdVisibility(View.VISIBLE);
                } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    setAdVisibility(View.GONE);
                }
            }
        };

        final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        mContext.registerReceiver(mScreenStateReceiver, filter);
    }

    private void unregisterScreenStateBroadcastReceiver() {
        try {
            mContext.unregisterReceiver(mScreenStateReceiver);
        } catch (Exception IllegalArgumentException) {
        }
    }

    public void loadAd() {
        if (mAdViewController != null) {
            mAdViewController.loadAd();
        }
    }

    public void setAdSize(AdSize adSize) {
        if (mAdViewController != null) {
            mAdViewController.setAdSize(adSize);
        }
    }

    public void destroy() {
        unregisterScreenStateBroadcastReceiver();
        removeAllViews();

        if (mAdViewController != null) {
            mAdViewController.destroy();
            mAdViewController = null;
        }
        mContext = null;
    }

    @Override
    protected void onWindowVisibilityChanged(final int visibility) {
        // Ignore transitions between View.GONE and View.INVISIBLE
        if (Visibility.hasScreenVisibilityChanged(mScreenVisibility, visibility)) {
            mScreenVisibility = visibility;
            setAdVisibility(mScreenVisibility);
        }
    }

    private void setAdVisibility(final int visibility) {
        if (mAdViewController == null) {
            return;
        }

        if (Visibility.isScreenVisible(visibility)) {
            mAdViewController.resumeRefresh();
        } else {
            mAdViewController.pauseRefresh();
        }
    }

    protected void adLoaded() {
        Logger.d("adLoaded");
        if (mAdListener != null) {
            mAdListener.onAdLoaded(this);
        }
    }

    protected void adFailed(AdError errorCode) {
        if (mAdListener != null) {
            mAdListener.onAdLoadFailed(this, errorCode);
        }
    }

    protected void adPresentedOverlay() {
        if (mAdListener != null) {
            mAdListener.onAdImpression(this);
        }
    }

    protected void adClicked() {
        if (mAdListener != null) {
            mAdListener.onAdClick(this);
        }
    }

    public void setPlacementId(String placementId) {
        if (mAdViewController != null) mAdViewController.setPlacementId(placementId);
    }

    public String getPlacementId() {
        return (mAdViewController != null) ? mAdViewController.getPlacementId() : null;
    }

    public void setRefreshTimeMillis(@Nullable final Integer refreshTimeMillis) {
        if (mAdViewController != null) {
            mAdViewController.setRefreshTimeMillis(refreshTimeMillis);
        }
    }


    public void setAutoRefresh(boolean enabled) {
        if (mAdViewController != null) {
            mAdViewController.setShouldAllowAutoRefresh(enabled);
        }
    }

    public boolean isAutoRefresh() {
        if (mAdViewController != null) {
            return mAdViewController.getCurrentAutoRefreshStatus();
        }
        return false;
    }


    public void forceRefresh() {
        if (mAdViewController != null) {
            mAdViewController.forceRefresh();
        }
    }

    public AdFormat getAdFormat() {
        return AdFormat.BANNER;
    }
}
